<template>
  <div class="container">
    <h3>vue+openlayers: 聚合数据示例</h3>
    <div id="vue-openlayers"></div>
    <div id="info"></div>
  </div>
</template>

<script>
import 'ol/ol.css';
import { Map,View} from 'ol';
import Tile from 'ol/layer/Tile';
import XYZ from 'ol/source/XYZ';
import VectorLayer from 'ol/layer/Vector';
import VectorSource from 'ol/source/Vector';
import { transform } from 'ol/proj';
import { Style, Circle, Stroke, Fill, Text } from 'ol/style';
import Cluster from 'ol/source/Cluster'; // 聚合数据源
import Point from 'ol/geom/Point';
import Feature from 'ol/Feature';
export default {
  name: 'polymerization',
  data() {
    return {
      map: null,
    }
  },
  mounted() {
    this.initMap();
  },
  methods: {
    initMap() {
      let count = 20000; // 聚合点的数量
      let features = [] // 聚合点的数据源
      let e = 15000000; // 范围
      for (let i = 0; i < count; ++i) {
        let coordinates = [2 * e * Math.random() - e, 2 * e * Math.random() - e]; // 随机生成坐标
        features[i] = new Feature(new Point(coordinates)); // 生成点
      }
      let clusterSource = new Cluster({
        distance: parseInt(40, 10) || 20, // 聚合的距离 默认20 parseint(40, 10) 10进制
        source: new VectorSource({
          features: features,
          wrapX: false
        })
      })
      let styleCache = {}; // 缓存样式
      let clusterLayer = new VectorLayer({
        source: clusterSource,
        style: feature => {
          let size = feature.get('features').length; // 获取聚合点的数量
          let style = styleCache[size]; // 获取缓存样式
          if (!style) {
            style = new Style({
              image: new Circle({
                radius: 10,
                stroke: new Stroke({
                  color: '#fff'
                }),
                fill: new Fill({
                  color: '#3399CC'
                })
              }),
              text: new Text({
                text: size.toString(),
                fill: new Fill({
                  color: '#fff'
                })
              })
            })
            styleCache[size] = style; // 缓存样式
          }
          return style;
        }
      })
      this.map = new Map({
        layers: [
          new Tile({
            source: new XYZ({
              url: 'http://wprd0{1-4}.is.autonavi.com/appmaptile?x={x}&y={y}&z={z}&lang=zh_cn&size=1&scl=1&style=7'
            })
          }),
          clusterLayer
        ],
        target: 'vue-openlayers',
        view: new View({
          center: transform([116.397411, 39.909186], 'EPSG:4326', 'EPSG:3857'),
          zoom: 2
        })
      })
    }
  }
}
</script>

<style scoped>
    .container {
        width: 100%;
        height: 780px;
        margin: 50px auto;
        border: 1px solid #42B983;
    }
    #vue-openlayers {
        width: 100%;
        height: 760px;
        margin: 0 auto;
        border: 1px solid #42B983;
        position: relative;
    }
</style>
